#include "var.h"

#define VAR_MAX_LIST 256
Var var[VAR_MAX_LIST];

static FILE *fp;
static char buf[VAR_LENGTH];

void init_var(void)
{
	int i = 0;
	
	for (i = 0; i < VAR_MAX_LIST; ++i) {
		var[i].var_name = NULL;
		var[i].var_value = NULL;
	}

	fp = fopen("diag.env", "r");

	if (fp == NULL)
		return;

	for (i = 0; i < VAR_MAX_LIST; ++i) {
		memset(buf, 0, sizeof(buf));
		if (fgets(buf, VAR_LENGTH - 1, fp)) {
			int j = 0;
			buf[strlen(buf)-1] = '\0';
			
			if (var[i].var_name == NULL) 
				var[i].var_name = (char*)malloc(VAR_LENGTH);
			if (var[i].var_value == NULL)
				var[i].var_value = (char*)malloc(VAR_LENGTH);

			memset(var[i].var_name, 0x0, VAR_LENGTH);
			memset(var[i].var_value, 0x0, VAR_LENGTH);
			#if 0
			sscanf(buf, "%s=%s\n", var[i].var_name, var[i].var_value); //TODO, why not work?
			#endif
			
			while (buf[j] != '\0') {
				if(buf[j] == '=')
					break;
				j++;
			}
			memcpy(var[i].var_name, buf, j);
			strcpy(var[i].var_value, buf + j + 1);	
		}	
		else
			break;
	}

	fclose(fp);
}

int save_var(void)
{
	int i = 0;

	fp = fopen("diag.env", "w");
	if (fp == NULL)
		return -1;

	for (i = 0; i < VAR_MAX_LIST; ++i) {
		if (var[i].var_value == NULL)
			break;
		sprintf(buf, "%s=%s\n", var[i].var_name, var[i].var_value);
		fputs(buf, fp);
	}

	fclose(fp);
	return 0;
}

int dump_var(void)
{
	int i = 0;
	Var *p_var;

	for (i = 0; i < VAR_MAX_LIST; ++i) {
		p_var = &var[i];
		if (p_var->var_name)
			show_var(p_var);
	}

	return 0;
}

void show_var(Var *pvar)
{
	printf("%s=%s\n", pvar->var_name, pvar->var_value);
}

/* find var by name 
** If found, return var*, else return NULL
*/
Var* find_var(char *name)
{
	int i = 0;

	for (i = 0; i < VAR_MAX_LIST; ++i) {
		if (var[i].var_name) {
			if (strcmp(var[i].var_name, name) == 0)
				return &var[i];
			}
		}

	return NULL;
}

/* update var by name */
int update_var(char *name, char *value)
{
	int i = 0;
	Var* p_var;

	for (i = 0; i < VAR_MAX_LIST; ++i) {
		p_var = find_var(name);
		if (p_var) {
			if (p_var->var_value)
				free(p_var->var_value);
			p_var->var_value = (char*)malloc(strlen(value) + 1);
			strcpy(p_var->var_value, value);
			return 0;
		} else {
			if (var[i].var_name == NULL) {
				var[i].var_name = (char*)malloc(strlen(name) + 1);
				strcpy(var[i].var_name, name);
				var[i].var_value = (char*)malloc(strlen(value) + 1);
				strcpy(var[i].var_value, value);
				return 0;
			}
		}
	}

	return -1;
}

/* delete var by name */
int del_var(char *name)
{
	int i = 0;

	for (i = 0; i < VAR_MAX_LIST; ++i) {
		if (var[i].var_name) {
			if (strcmp(var[i].var_name, name) == 0) {
				if (var[i].var_name) {
					free(var[i].var_name);
					var[i].var_name = NULL;
				}
				if (var[i].var_value) {
					free(var[i].var_value);
					var[i].var_value = NULL;
				}

				return 0;
			}
		}
	}

	return -1;
}
